﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Media.Animation;
using myTwitter.BO;
using System.Collections.ObjectModel;
using myTwitter.CustomControls;
using System.Collections;
using System.Text.RegularExpressions;
using myTwitter.API;

namespace myTwitter
{
	/// <summary>
	/// Interaction logic for Navigator.xaml
	/// </summary>
	public partial class Navigator
	{
        private enum iMessageControls
        {
            AllMessages, DirectMessages, Mentions, Search
        }

        private bool _searchControlOpened = false;
        private bool _searchTbxFirstFocus = true;
        private Storyboard _openSearchControlSB;
        private Storyboard _closeSearchControlSB;
        private Storyboard _hideNewTwittControlSB;
        private myTwitter.API.StatusUpdatedHandler _statusUpdatedCallback;
        private bool _statusUpdateCompleted, _searchUpdateCompleted, _mentionsUpdateCompleted, _directMessagesUpdateCompleted;

		public Navigator()
		{
			this.InitializeComponent();
            GlobalController.Views.Navigator = this;
            _openSearchControlSB = this.Resources["ShowSearchControl"] as Storyboard;
            _closeSearchControlSB = this.Resources["HideSearchControl"] as Storyboard;
            _hideNewTwittControlSB = this.Resources["HideNewTwittControl"] as Storyboard;
            _statusUpdatedCallback = new myTwitter.API.StatusUpdatedHandler(ITwitterProvider_StatusUpdated);
            _showHideSearchBt.Click += new RoutedEventHandler(_showHideSearchBt_Click);
            _searchTbx.GotFocus += new RoutedEventHandler(_searchTbx_GotFocus);
            _searchTbx.KeyUp += new KeyEventHandler(_searchTbx_KeyUp);
            _doSearchBt.Click += new RoutedEventHandler(_doSearchBt_Click);
            _sendBt.Click += new RoutedEventHandler(_sendBt_Click);
            _cancelBt.Click += new RoutedEventHandler(_cancelBt_Click);
            _tabControl.SelectionChanged += new SelectionChangedEventHandler(_tabControl_SelectionChanged);
            _newTwittBt.Click += new RoutedEventHandler(_newTwittBt_Click);            
		}

        //private bool _synchedWithTwitterProvider;

        public void SyncWithTwitterProvider()
        {
            GlobalController.Instances.ITwitterProvider.StatusUpdated += new myTwitter.API.StatusUpdatedHandler(ITwitterProvider_StatusUpdated);
            GlobalController.Instances.ITwitterProvider.SearchCompleted += new myTwitter.API.SearchCompletedHandler(ITwitterProvider_SearchCompleted);
            GlobalController.Instances.ITwitterProvider.MentionsUpdated += new myTwitter.API.MentionsUpdatedHandler(ITwitterProvider_MentionsUpdated);
            GlobalController.Instances.ITwitterProvider.DirectMessagesUpdated += new myTwitter.API.DirectMessagesUpdatedHandler(ITwitterProvider_DirectMessagesUpdated);
            //_synchedWithTwitterProvider = true;
        }

        void _newTwittBt_Click(object sender, RoutedEventArgs e)
        {
            _textMsg.Focus();
        }
        
        bool _ignoreTextChange = false;
        int _lastEditIndex = 0;

        void _textMsg_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (_ignoreTextChange)
            {
                _ignoreTextChange = false;
                _textMsg.SelectionStart = _lastEditIndex;
                return;
            }

            if (e.Changes.Count == 1)
            {
                foreach (TextChange change in e.Changes)
                {
                    string modifiedText = _textMsg.Text.Substring(change.Offset, change.AddedLength);
                    bool isHyperlink = IsHyperlink(modifiedText);
                    if (isHyperlink)
                    {
                        string tinyUrl = TinyUrl.GetTinyUrl(modifiedText);
                        string newText = _textMsg.Text;
                        newText = _textMsg.Text.Replace(modifiedText, tinyUrl);
                        _lastEditIndex = newText.LastIndexOf(tinyUrl) + tinyUrl.Length;
                        _ignoreTextChange = true;                        
                        _textMsg.Text = newText;
                        
                    }
                }                
            }
        }

        private bool IsHyperlink(string word)
        {
            Regex regex = new Regex(@"(https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*");
            Match match = regex.Match(word);
            if (match.Length > 0)
                return true;
            else
                return false;
        }

        void _tabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            /*
            if (_tabControl.SelectedItem == _allTwiitsTab)
                GlobalController.Views.IMessagesControl = _allIMessagesControl;

            if (_tabControl.SelectedItem == _directMessagesTab)
                GlobalController.Views.IMessagesControl = _dmIMessagesControl;

            if (_tabControl.SelectedItem == _searchTab)
                GlobalController.Views.IMessagesControl = _searchIMessagesControl;

            if (_tabControl.SelectedItem == _mentionsTab)
                GlobalController.Views.IMessagesControl = _mentionsIMessagesControl;*/
        }

        void _searchIMessagesControl_Loaded(object sender, RoutedEventArgs e)
        {
            UpdateMessagesControlState(iMessageControls.Search);
        }

        void _dmIMessagesControl_Loaded(object sender, RoutedEventArgs e)
        {
            UpdateMessagesControlState(iMessageControls.DirectMessages);
        }

        void _mentionsIMessagesControl_Loaded(object sender, RoutedEventArgs e)
        {
            UpdateMessagesControlState(iMessageControls.Mentions);
        }

        void _allIMessagesControl_Loaded(object sender, RoutedEventArgs e)
        {
            UpdateMessagesControlState(iMessageControls.AllMessages);
        }

        void ITwitterProvider_DirectMessagesUpdated(List<DirectMessage> updatedDirectMessages)
        {
            _directMessagesUpdateCompleted = true;
            UpdateMessagesControlState(iMessageControls.DirectMessages);
            UpdateMessagesControlState(iMessageControls.AllMessages);
        }

        void ITwitterProvider_MentionsUpdated(List<Status> updatedstatus)
        {
            _mentionsUpdateCompleted = true;
            UpdateMessagesControlState(iMessageControls.Mentions);
            UpdateMessagesControlState(iMessageControls.AllMessages);
        }

        void ITwitterProvider_SearchCompleted(List<IMessage> entries)
        {
            _searchUpdateCompleted = true;
            UpdateMessagesControlState(iMessageControls.Search);
            _searchTbx.IsEnabled = true;
        }

        void ITwitterProvider_StatusUpdated(List<Status> updatedstatus)
        {
            _statusUpdateCompleted = true;
            UpdateMessagesControlState(iMessageControls.AllMessages);
        }

        void UpdateMessagesControlState(iMessageControls control)
        {
            /*
            switch (control)
            {
                case iMessageControls.AllMessages:
                    if (!_mentionsUpdateCompleted && !_directMessagesUpdateCompleted && !_statusUpdateCompleted)
                        _allIMessagesControl.SwitchToLoadingMode();
                    else
                        _allIMessagesControl.StopLoadingMode();
                    break;

                case iMessageControls.DirectMessages:
                    if (!_directMessagesUpdateCompleted)
                        _dmIMessagesControl.SwitchToLoadingMode();
                    else
                        _dmIMessagesControl.StopLoadingMode();
                    break;

                case iMessageControls.Mentions:
                    if (!_mentionsUpdateCompleted)
                        _mentionsIMessagesControl.SwitchToLoadingMode();
                    else
                        _mentionsIMessagesControl.StopLoadingMode();
                    break;

                case iMessageControls.Search:
                    {
                        if (!_searchUpdateCompleted)
                            _searchIMessagesControl.SwitchToLoadingMode();
                        else 
                            _searchIMessagesControl.StopLoadingMode();
                    }

                    break;
            }*/
        }
            

        void _searchTbx_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                _doSearchBt_Click(sender, null);
            }
            if (string.IsNullOrEmpty(_searchTbx.Text))
                _doSearchBt.IsEnabled = false;
            else
                _doSearchBt.IsEnabled = true;
        }

        void _cancelBt_Click(object sender, RoutedEventArgs e)
        {
            this.BeginStoryboard(_hideNewTwittControlSB);
        }

        void _sendBt_Click(object sender, RoutedEventArgs e)
        {
            GlobalController.Instances.ITwitterProvider.UpdateStatus(_textMsg.Text);
            this.BeginStoryboard(_hideNewTwittControlSB);
            _textMsg.Text = string.Empty;
        }

        void _doSearchBt_Click(object sender, RoutedEventArgs e)
        {
            _searchTbx.IsEnabled = false;
            GlobalController.Instances.ITwitterProvider.Search(_searchTbx.Text);
            _searchTab.Visibility = Visibility.Visible;
            _tabControl.SelectedItem = _searchTab;

            //_searchIMessagesControl._preLoader.Start();
        }


        void _searchTbx_GotFocus(object sender, RoutedEventArgs e)
        {
            if (_searchTbxFirstFocus)
                _searchTbx.Text = string.Empty;
            _searchTbxFirstFocus = false;
        }

        void _showHideSearchBt_Click(object sender, RoutedEventArgs e)
        {
            if (_searchControlOpened)
                this.BeginStoryboard(_closeSearchControlSB);
            else
            {
                _searchTbx.Focus();
                this.BeginStoryboard(_openSearchControlSB);
            }
            
            _searchControlOpened = !_searchControlOpened;
        }
	}
}